<script lang="ts" setup>
import { computed, onMounted, reactive, ref, UnwrapRef } from "vue";
import {
  DeleteOutlined,
  SearchOutlined,
  PictureOutlined,
  IdcardOutlined
} from "@ant-design/icons-vue";
import {
  delPictureUsingPost, doPictureReviewUsingPost, listPictureByPageUsingPost,
  listPictureVoByPageUsingPost
} from "@/api/PictureController";
import { message, Modal } from "ant-design-vue";
import {PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_OPTIONS} from "../../constants/picture";
import dayjs from "dayjs";

interface FormState {
  layout: 'horizontal' | 'vertical' | 'inline';
  fieldA: string;
  fieldB: string;
}

const formState: UnwrapRef<FormState> = reactive({
  layout: 'horizontal',
  fieldA: '',
  fieldB: '',
});

// 表格数据相关
const dataList = ref<API.Picture[]>([]);
const total = ref<number>(0);
const loading = ref(false);
const previewVisible = ref(false);
const currentPreviewUrl = ref('');

// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  pageSize: 10,
  current: 1,
  sortOrder: 'ascend',
  sortField: 'createTime'
});

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80,
    sorter: true
  },
  {
    title: '图片',
    dataIndex: 'url',
    width: 150
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage'
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: 150
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true
  },
  {
    title: '类型',
    dataIndex: 'category',
    width: 100
  },
  {
    title: '标签',
    dataIndex: 'tags',
    width: 120
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
    width: 150
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    width: 120
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 160,
    fixed: 'right'
  }
];

// 获取数据
const getData = async () => {
  try {
    loading.value = true;
    const res = await listPictureByPageUsingPost(searchParams);
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records ?? [];
      total.value = res.data.data.total ?? 0;
    } else {
      message.error('数据获取失败：' + res.data.message);
    }
  } catch (e) {
    message.error('请求异常');
  } finally {
    loading.value = false;
  }
};

// 分页配置
const pagination = computed(() => ({
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
}));

// 表格变化处理
const doTableChange = (page: any, filters: any, sorter: any) => {
  searchParams.current = page.current;
  searchParams.pageSize = page.pageSize;
  if (sorter.field) {
    searchParams.sortField = sorter.field;
    searchParams.sortOrder = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  getData();
};

// 搜索处理
const doSearch = () => {
  searchParams.current = 1;
  getData();
};

// 删除图片
const doDel = async (id: number) => {
  try {
    const res = await delPictureUsingPost({ id });
    if (res.data.code === 0) {
      message.success('删除成功');
      await getData();
    } else {
      message.error('删除失败：' + res.data.message);
    }
  } catch (e) {
    message.error('删除操作异常');
  }
};

// 预览图片
const showPreview = (url: string) => {
  currentPreviewUrl.value = url;
  previewVisible.value = true;
};

const handleReview = async (record: API.Picture, reviewStatus: number) =>{
  const reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? "管理员自动过审" : "管理员操作拒绝"
  const res = await doPictureReviewUsingPost({
    id: record.id,
    reviewStatus,
    reviewMessage
  })
  if (res.data.code === 0){
    message.success('审核操作成功')
    getData()
  }else {
    message.error('审核操作失败' + res.data.message)
  }
}

onMounted(() => {
  getData();
});
</script>

<template>
  <div class="picture-management-container">
    <!-- 图片预览模态框 -->
    <Modal
        :visible="previewVisible"
        :footer="null"
        @cancel="previewVisible = false"
        width="80vw"
        centered
    >
      <img :src="currentPreviewUrl" class="preview-modal-image" />
    </Modal>

    <!-- 搜索区域 -->
    <div class="search-card">
      <div class="search-header">
        <div class="search-gradient"></div>
        <h2 class="search-title">🔍 图片资源管理</h2>
        <p class="search-subtitle">精准定位您的视觉资产</p>
      </div>
      
      <a-form @finish="doSearch" class="search-form">
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="关键词">
              <a-input
                  v-model:value="searchParams.searchText"
                  placeholder="图片名称/描述"
                  allow-clear
                  class="neon-input"
              >
                <template #prefix>
                  <SearchOutlined class="input-icon" />
                </template>
              </a-input>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="类型">
              <a-select
                  v-model:value="searchParams.category"
                  placeholder="选择分类"
                  class="neon-select"
                  allow-clear
              >
                <a-select-option value="nature">自然</a-select-option>
                <a-select-option value="technology">科技</a-select-option>
                <a-select-option value="art">艺术</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="标签">
              <a-select
                  v-model:value="searchParams.tags"
                  mode="tags"
                  placeholder="添加标签"
                  class="neon-tags"
                  allow-clear
              >
                <a-select-option value="精选">精选</a-select-option>
                <a-select-option value="热门">热门</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="12" :md="8" :lg="6">
            <a-form-item label="审核状态">
              <a-select
                  v-model:value="searchParams.reviewStatus"
                  placeholder="选择状态"
                  :options="PIC_REVIEW_STATUS_OPTIONS"
                  class="neon-tags"
                  allow-clear
              />
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="24" :md="24" :lg="24">
            <a-form-item class="search-action">
              <button class="glow-button" type="submit">
                <span class="btn-text">立即搜索</span>
                <div class="hover-glow"></div>
              </button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="data-table-card">
      <div class="table-header">
        <span class="table-title">📁 图片资源库</span>
        <span class="table-count">共 {{ total }} 项资产</span>
      </div>

      <a-table
          :columns="columns"
          :data-source="dataList"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1200 }"
          @change="doTableChange"
          class="modern-table"
          bordered
      >
        <template #bodyCell="{ column, record }">
          <!-- 图片列 -->
          <template v-if="column.dataIndex === 'url'">
            <div class="image-preview" @click="showPreview(record.url)">
              <img
                  :src="record.url"
                  alt="图片预览"
                  class="preview-image"
              />
              <div class="image-hover">
                <span class="view-text">查看大图</span>
              </div>
            </div>
          </template>

          <!-- 标签列 -->
          <template v-else-if="column.dataIndex === 'tags'">
            <div class="tag-cloud">
              <a-tag
                  v-for="tag in JSON.parse(record.tags || '[]')"
                  :key="tag"
                  color="blue"
              >
                {{ tag }}
              </a-tag>
            </div>
          </template>

          <!-- 图片信息列 -->
          <template v-else-if="column.dataIndex === 'picInfo'">
            <div class="info-grid">
              <div class="info-item">
                <span class="info-label">格式：</span>
                <span class="info-value">{{ record.picFormat }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分辨率：</span>
                <span class="info-value">{{ record.picWidth }}×{{ record.picHeight }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">大小：</span>
                <span class="info-value">{{ (record.picSize / 1024).toFixed(2) }} KB</span>
              </div>
            </div>
          </template>

          <!-- 审核信息列 -->
          <template v-else-if="column.dataIndex === 'reviewMessage'">
            <div class="review-info">
              <div class="status-tag">
                <a-tag :color="record.reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? 'green' : 'red'">
                  {{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}
                </a-tag>
              </div>
              <div class="review-detail">
                <div>审核人：{{ record.reviewerId || '-' }}</div>
                <div>{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm') }}</div>
                <div class="review-message">{{ record.reviewMessage }}</div>
              </div>
            </div>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <div class="action-buttons">
              <a-space>
                <a-button
                    v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
                    @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
                    type="primary"
                    ghost
                    size="small"
                >
                  通过
                </a-button>
                <a-button
                    v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
                    @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
                    danger
                    ghost
                    size="small"
                >
                  拒绝
                </a-button>
                <a-popconfirm
                    title="确定要删除该图片吗？"
                    @confirm="doDel(record.id)"
                    ok-text="确定"
                    cancel-text="取消"
                >
                  <a-button
                      type="link"
                      danger
                      size="small"
                  >
                    <DeleteOutlined />
                  </a-button>
                </a-popconfirm>
              </a-space>
            </div>
            <div class="action-buttons">
              <a-tooltip title="编辑元数据">
                <a-button
                    type="link"
                    class="edit-btn"
                    :href="`/add_picture?id=${record.id}`"
                >
                  <svg class="icon" viewBox="0 0 24 24">
                    <path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
                  </svg>
                </a-button>
              </a-tooltip>

              <a-popconfirm
                  title="确定要删除该图片吗？"
                  @confirm="doDel(record.id)"
                  ok-text="确定"
                  cancel-text="取消"
              >
                <a-tooltip title="永久删除">
                  <a-button
                      type="link"
                      danger
                      class="delete-btn"
                  >
                    <svg class="icon" viewBox="0 0 24 24">
                      <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                    </svg>
                  </a-button>
                </a-tooltip>
              </a-popconfirm>
            </div>
          </template>
        </template>

        <!-- 加载状态 -->
        <template #empty>
          <div class="loading-overlay" v-if="loading">
            <div class="loading-wave">
              <div class="wave"></div>
              <div class="wave"></div>
              <div class="wave"></div>
            </div>
            <span class="loading-text">正在加载视觉资产...</span>
          </div>
        </template>
      </a-table>
    </div>
  </div>
</template>

<style scoped lang="less">
@keyframes gradientFlow {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

.picture-management-container {
  padding: 2rem;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  min-height: 100vh;
}

.search-card {
  background: rgba(30, 41, 59, 0.8);
  border-radius: 1.5rem;
  padding: 2rem;
  margin-bottom: 2rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(99, 102, 241, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

  .search-header {
    position: relative;
    margin-bottom: 2rem;

    .search-gradient {
      position: absolute;
      top: -50px;
      left: 50%;
      width: 200%;
      height: 200px;
      background: radial-gradient(circle, rgba(99, 102, 241, 0.1) 0%, transparent 70%);
      transform: translateX(-50%);
      z-index: 0;
    }

    .search-title {
      color: #e2e8f0;
      font-size: 1.8rem;
      text-align: center;
      position: relative;
      z-index: 1;
    }

    .search-subtitle {
      color: #94a3b8;
      text-align: center;
      margin-top: 0.5rem;
    }
  }
}

.search-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1.5rem;
}

.neon-input, .neon-select, .neon-tags {
  background: rgba(15, 23, 42, 0.7) !important;
  border: 1px solid rgba(99, 102, 241, 0.3) !important;
  border-radius: 12px !important;
  color: #e2e8f0 !important;
  transition: all 0.3s ease;

  &:hover {
    border-color: #818cf8 !important;
    box-shadow: 0 0 12px rgba(129, 140, 248, 0.2) !important;
  }

  &:focus {
    box-shadow: 0 0 20px rgba(129, 140, 248, 0.3) !important;
  }
}

.glow-button {
  position: relative;
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  padding: 0.8rem 2rem;
  border-radius: 8px;
  color: white;
  font-weight: 500;
  overflow: hidden;
  transition: all 0.3s ease;

  .btn-text {
    position: relative;
    z-index: 2;
  }

  .hover-glow {
    position: absolute;
    width: 150%;
    height: 150%;
    background: radial-gradient(circle, rgba(255,255,255,0.15) 0%, transparent 60%);
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    transform: translateY(-2px);

    .hover-glow {
      opacity: 1;
    }
  }
}

.data-table-card {
  background: rgba(30, 41, 59, 0.8);
  border-radius: 1.5rem;
  padding: 2rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(99, 102, 241, 0.2);

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;

    .table-title {
      color: #e2e8f0;
      font-size: 1.4rem;
      font-weight: 600;
    }

    .table-count {
      color: #94a3b8;
      font-size: 0.9rem;
    }
  }
}

.modern-table {
  :deep(.ant-table-thead > tr > th) {
    background: linear-gradient(45deg, #6366f1, #8b5cf6) !important;
    color: white !important;
    font-weight: 500;
    border: none !important;
  }

  :deep(.ant-table-tbody > tr) {
    background: rgba(15, 23, 42, 0.5);
    transition: all 0.3s ease;

    &:hover {
      background: rgba(99, 102, 241, 0.1) !important;
      transform: translateX(10px);
    }

    &:nth-child(even) {
      background: rgba(15, 23, 42, 0.3);
    }
  }

  :deep(.ant-table-cell) {
    color: #e2e8f0 !important;
    border-color: rgba(99, 102, 241, 0.2) !important;
  }
}

.image-preview {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  .image-hover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;

    .view-text {
      color: white;
      font-size: 0.8rem;
    }
  }

  &:hover {
    .preview-image {
      transform: scale(1.1);
    }

    .image-hover {
      opacity: 1;
    }
  }
}

.tag-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;

  .tag-item {
    background: rgba(99, 102, 241, 0.15);
    color: #818cf8;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(99, 102, 241, 0.3);
      transform: translateY(-2px);
    }
  }
}

.info-grid {
  display: grid;
  gap: 8px;

  .info-item {
    display: flex;
    justify-content: space-between;

    .info-label {
      color: #94a3b8;
    }

    .info-value {
      color: #e2e8f0;
      font-weight: 500;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 12px;

  .icon {
    width: 20px;
    height: 20px;
    fill: currentColor;
    transition: all 0.3s ease;
  }

  .edit-btn {
    color: #818cf8;

    &:hover {
      color: #6366f1;
      transform: rotate(15deg);
    }
  }

  .delete-btn {
    color: #f87171;

    &:hover {
      color: #ef4444;
      transform: scale(1.1);
    }
  }
}

.loading-overlay {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .loading-wave {
    display: flex;
    gap: 8px;
    margin-bottom: 1rem;

    .wave {
      width: 4px;
      height: 24px;
      background: #6366f1;
      animation: wave 1s ease-in-out infinite;

      &:nth-child(2) { animation-delay: 0.2s }
      &:nth-child(3) { animation-delay: 0.4s }
    }
  }

  .loading-text {
    color: #94a3b8;
  }
}

@keyframes wave {
  0%, 100% { transform: scaleY(1) }
  50% { transform: scaleY(1.5) }
}

@media (max-width: 768px) {
  .picture-management-container {
    padding: 1rem;
  }

  .search-card {
    padding: 1.5rem;
    border-radius: 1rem;
  }

  .search-form {
    grid-template-columns: 1fr;
  }
}
.preview-modal-image {
  width: 100%;
  height: 80vh;
  object-fit: contain;
  border-radius: 8px;
}

.review-info {
  display: flex;
  align-items: flex-start;
  gap: 8px;

  .status-tag {
    flex-shrink: 0;
  }

  .review-detail {
    flex: 1;
    font-size: 12px;
    color: #e2e8f0;

    .review-message {
      color: #94a3b8;
      margin-top: 4px;
    }
  }
}

.action-buttons {
  .ant-btn {
    padding: 0 8px;
    height: 28px;
  }
}

@media (max-width: 768px) {
  .search-form {
    .ant-col {
      padding: 0 8px;
    }
  }

  .modern-table {
    :deep(.ant-table-thead > tr > th),
    :deep(.ant-table-tbody > tr > td) {
      padding: 12px 8px !important;
    }
  }
}
</style>
